import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:thingskit/Pages/DeviceSetting/all_collapse/group_collapse.dart';
import 'package:thingskit/Pages/DeviceSetting/all_collapse/light_collapse.dart';
import 'package:thingskit/Pages/DeviceSetting/all_collapse/rf_collapse.dart';
import 'package:thingskit/apiService/mode.dart';
import 'package:thingskit/components/titleCard.dart';

import '../../components/aRowBottons.dart';
import '../../components/functionButton.dart';
import '../../components/lightContent.dart';
import '../../components/selectBox.dart';
import '../../components/showModeDescription.dart';
import '../../components/singleRowCard.dart';
import '../../utils/ToastController.dart';
import '../../utils/UsbController.dart';
import '../../utils/const.dart';
import 'all_collapse/sub_collapse.dart';
import 'config_data.dart';

class DeviceSettingController extends GetxController {
  RxList<Mode> modeList = <Mode>[].obs; // 响应式列表
  Rx<Mode?> selectedMode = Rx<Mode?>(null); // 响应式选中项
}

class DeviceSettingPage extends StatefulWidget {
  @override
  _DeviceSettingPageState createState() => _DeviceSettingPageState();
}

class _DeviceSettingPageState extends State<DeviceSettingPage> {
  final UsbController usbController = Get.find();
  final ToastController toastController = Get.find();
  final DeviceSettingController DSC = Get.put(DeviceSettingController());
  String? selectedAddress;
  String _selectedGroup = '请选择分组';
  bool isExpanded = false;
  final modeNameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text('设备配置')),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Obx(
              () => ARowBottons(
                title1: usbController.isDebugging.value ? '关闭串口调试' : '开启串口调试',
                color1:
                    usbController.isDebugging.value ? Colors.red : Colors.green,
                onPressed1: usbController.openSerialPortDebug,
                title2: '上下翻转',
                color2: Colors.purple,
                onPressed2: usbController.turnOver,
              ),
            ),
            SizedBox(height: 6),
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      Text('分组', style: TextStyle(fontSize: 18)),
                      SizedBox(width: 10),
                      SelectBox(
                        initialValue: _selectedGroup,
                        options: groupOptions,
                        label: '请选择分组',
                        onChanged: (value) {
                          setState(() {
                            _selectedGroup = value;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 10),
                Expanded(
                  child: FunctionButton(
                    onPressed: () {
                      selectedAddress = null;
                      showLights();
                      usbController.searchLight();
                    },
                    title: '搜灯',
                    color: Colors.blue,
                  ),
                ),
              ],
            ),
            showALightRow(),
            Expanded(
              flex: 1,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: 100,
                    child: Column(
                      children: [
                        Container(
                          height: 46,
                          color: Color(0xFFD3D3D3),
                          child: TitleCard(title: '基础配置'),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(children: [SubCollapse()]),
                    ),
                  ),
                ],
              ),
            ),
            Column(
              children: [
                ARowBottons(
                  title1: '保存方案',
                  color1: Colors.blue,
                  onPressed1: showSaveConfig,
                  title2: '选择方案',
                  color2: Colors.blue,
                  onPressed2: showModeList,
                ),
                SizedBox(height: 8),
                ARowBottons(
                  title1: '清空属性',
                  color1: Colors.yellow,
                  onPressed1: () {
                    clearConfig();
                    setState(() {});
                  },
                  title2: '确认下发',
                  color2: Colors.blue,
                  onPressed2: confirmConfig,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //点击搜灯后的弹窗
  void showLights() {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.white,
        title: Center(
          child: Text('搜灯详情', style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        contentPadding: EdgeInsets.symmetric(horizontal: 6, vertical: 8),
        content: Container(
          constraints: BoxConstraints(
            maxHeight: Get.height * 0.8,
            maxWidth: Get.width * 0.8,
          ),
          child: StatefulBuilder(
            builder: (context, setBuliderState) {
              return Column(
                // 关键：收缩内容高度
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 340,
                    width: 300,
                    child: Obx(
                      () => ListView.builder(
                        shrinkWrap: true,
                        itemCount: usbController.Lights.length,
                        itemBuilder: (context, index) {
                          final light = usbController.Lights[index];
                          return SingleRowCard(
                            content: LightContent(index: index),
                            isChecked: selectedAddress == light['addr'],
                            onCheckChange: (newValue) {
                              setBuliderState(() {
                                selectedAddress =
                                    newValue == true ? light['addr'] : null;
                              });
                            },
                            onClick: () {
                              usbController.lightInfo(light['addr']);
                            },
                          );
                        },
                      ),
                    ),
                  ),
                  ARowBottons(
                    title1: '闪一闪',
                    color1: Colors.blue,
                    onPressed1: () => usbController.flash(selectedAddress),
                    title2: '停止闪',
                    color2: Colors.blue,
                    onPressed2: () => usbController.stopFlash(selectedAddress),
                  ),
                  SizedBox(height: 6),
                  ARowBottons(
                    title1: '取消',
                    color1: Colors.red,
                    onPressed1: () {
                      if (Get.isDialogOpen!) Get.back();
                    },
                    title2: '确认',
                    color2: Colors.green,
                    onPressed2: () {
                      if (selectedAddress != null) {
                        if (Get.isDialogOpen!) Get.back();
                        setState(() {});
                      } else {
                        toastController.showCenterToast('请选择一个灯');
                      }
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  // 显示选中的灯
  Widget showALightRow() {
    if (selectedAddress == null) return SizedBox(height: 60);
    final index = usbController.Lights.indexWhere(
      (element) => element['addr'] == selectedAddress,
    );
    return Column(
      children: [
        SizedBox(height: 6),
        SingleRowCard(
          isChecked: true,
          content: LightContent(index: index),
          onClick: () {
            usbController.lightInfo(usbController.Lights[index]['addr']);
          },
        ),
      ],
    );
  }

  //初始化方案列表
  DeviceConfigData getConfig() {
    final SubCollapseController subCollapseController = Get.find();
    final LightCollapseController lightCollapseController = Get.find();
    final GroupCollapseController groupCollapseController = Get.find();
    final RfCollapseController rfCollapseController = Get.find();
    return DeviceConfigData(
      isLightMode: subCollapseController.isLightMode.value,
      isGroupConfig: subCollapseController.isGroupConfig.value,
      isRFConfig: subCollapseController.isRFconfig.value,
      firstGroup: int.tryParse(groupCollapseController.firstGroup.text) ?? 0,
      secondGroup: int.tryParse(groupCollapseController.secondGroup.text) ?? 0,
      mode: lightCollapseController.mode.value,
      fixedBrightness:
          int.tryParse(lightCollapseController.fixedBrightness.text) ?? 0,
      lightDelayTime:
          int.tryParse(lightCollapseController.lightDelayTime.text) ?? 0,
      peopleBrightness:
          int.tryParse(lightCollapseController.peopleBrightness.text) ?? 0,
      noPeopleBrightness:
          int.tryParse(lightCollapseController.noPeopleBrightness.text) ?? 0,
      darkDelayTime:
          int.tryParse(lightCollapseController.darkDelayTime.text) ?? 0,
      isForwarding: rfCollapseController.isForward.value,
      ttlCount: int.tryParse(rfCollapseController.ttlCount.text) ?? 0,
      isNetwork: rfCollapseController.isNetwork.value,
      power: rfCollapseController.power.value.toInt(),
      isSecondGroup: groupCollapseController.isSecondGroup.value,
    );
  }

  //显示当前方案
  void showSaveConfig() {
    final focusNode = FocusNode();
    Get.dialog(
      SimpleDialog(
        backgroundColor: Colors.white,
        title: Center(
          child: Text('方案详情', style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
        children: [
          ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: Get.width * 0.8,
              maxHeight: Get.height * 0.8,
            ),
            child: Column(
              // 关键：收缩内容高度
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: modeNameController,
                  keyboardType: TextInputType.text,
                  focusNode: focusNode,
                  onTapOutside: (e) {
                    focusNode.unfocus();
                  },
                  decoration: InputDecoration(
                    hintText: '请输入方案名称',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: Colors.grey),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      vertical: 10.0,
                      horizontal: 12.0,
                    ),
                  ),
                ),
                SizedBox(height: 10),
                ShowModeDescription(mode: jsonEncode(getConfig().toJson())),
                SizedBox(height: 10),
                SizedBox(
                  width: 200,
                  child: FunctionButton(
                    onPressed: () async {
                      final result = await saveConfig();
                      if (result) {
                        Get.back();
                        clearConfig();
                        toastController.showCenterToast('方案保存成功');
                      }
                    },
                    title: '保存',
                    color: Colors.blue,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  //保存方案
  Future<bool> saveConfig() async {
    if (modeNameController.text.isEmpty) {
      toastController.showCenterToast('方案名称不能为空');
      return false;
    }
    final data = getConfig();
    final result = await ModeApi().createMode(
      modeNameController.text,
      jsonEncode(data.toJson()),
    );
    if (result == null) {
      toastController.showCenterToast('方案保存失败');
      return false;
    } else {
      return true;
    }
  }

  // 显示方案列表
  Future<void> showModeList() async {
    DSC.selectedMode.value = null;
    DSC.modeList.value = await ModeApi().getModeList();
    Get.dialog(
      SimpleDialog(
        backgroundColor: Colors.white,
        title: Center(
          child: Text('方案列表', style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
        children: [
          SizedBox(height: 10),
          ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: Get.width * 0.8,
              maxHeight: Get.height * 0.8,
            ),
            child: StatefulBuilder(
              builder: (context, setBuliderState) {
                return Column(
                  // 关键：收缩内容高度
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 360,
                      width: 300,
                      child: Obx(
                        () => ListView.builder(
                          itemCount: DSC.modeList.length,
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return Column(
                              children: [
                                Row(
                                  children: [
                                    Obx(
                                      () => Radio(
                                        groupValue:
                                            DSC.selectedMode.value?.id ?? 0,
                                        value: DSC.modeList[index].id,
                                        activeColor: Colors.blue,
                                        onChanged: (newValue) {
                                          setBuliderState(() {
                                            DSC.selectedMode.value =
                                                DSC.modeList[index];
                                          });
                                        },
                                      ),
                                    ),
                                    Expanded(
                                      child: Text(
                                        DSC.modeList[index].name,
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 1,
                                        style: TextStyle(fontSize: 18),
                                      ),
                                    ),
                                  ],
                                ),
                                Divider(height: 1, color: Colors.grey),
                              ],
                            );
                          },
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    ARowBottons(
                      title1: '取消',
                      color1: Colors.red,
                      onPressed1: () => Get.back(),
                      title2: '确认',
                      color2: Colors.green,
                      onPressed2: confirmMode,
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  //确认选择方案
  void confirmMode() {
    final SubCollapseController subCollapseController = Get.find();
    final LightCollapseController lightCollapseController = Get.find();
    final GroupCollapseController groupCollapseController = Get.find();
    final RfCollapseController rfCollapseController = Get.find();
    if (DSC.selectedMode.value == null) {
      toastController.showCenterToast('请选择方案');
      Get.back();
      return;
    }
    Map<String, dynamic> data = jsonDecode(DSC.selectedMode.value!.content);
    subCollapseController.setModeFromJson(data);
    lightCollapseController.setModeFromJson(data);
    groupCollapseController.setModeFromJson(data);
    rfCollapseController.setModeFromJson(data);
    Get.back();
  }

  //清空配置属性
  void clearConfig() {
    final SubCollapseController subCollapseController = Get.find();
    final LightCollapseController lightCollapseController = Get.find();
    final GroupCollapseController groupCollapseController = Get.find();
    final RfCollapseController rfCollapseController = Get.find();
    subCollapseController.setDefault();
    lightCollapseController.setDefault();
    groupCollapseController.setDefault();
    rfCollapseController.setDefault();
  }

  //确认下发
  void confirmConfig() {
    if (_selectedGroup != '请选择分组' && _selectedGroup.isNotEmpty) {
      usbController.setGroupDevice(_selectedGroup, getConfig().toJson());
      return;
    }
    if (selectedAddress != null) {
      usbController.setConfigDevice(selectedAddress!, getConfig().toJson());
      return;
    }
    toastController.showCenterToast('请选择灯或分组');
  }
}
